package com.apes.hr.base.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.hr.base.model.*;
import com.apes.hr.base.repository.SkillTypeRepository;
import com.apes.hr.base.repository.TalentPoolRepository;
import com.apes.hr.recruit.model.RecruitChannel;
import com.apes.hr.recruit.repository.RecruitChannelRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 功能：HR-人才储备库
 *
 * @author linwz
 * @create 2019-03-11 14:35
 */
@Service("hrTalentPoolService")
public class TalentPoolService extends DomainService {

    @Autowired
    TalentPoolRepository talentPoolRepository;
    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    SkillTypeRepository skillTypeRepository;
    @Autowired
    SequenceService sequenceService;
    @Autowired
    RecruitChannelRepository recruitChannelRepository;
    @Autowired
    PostRepository postRepository;
    @Autowired
    private DeptRepository deptRepository;

    public TalentPool save(SimpleRequest request) {
        TalentPool employee = request.getO(TalentPool.class);
        return createAndUpdate(employee);
    }


    public TalentPool createAndUpdate(TalentPool employee) {
        employee.setState("create");
        return talentPoolRepository.saveAndFlush(employee);
    }

    public TalentPool update(SimpleRequest request) {
        TalentPool employee = request.getO(TalentPool.class);
        return talentPoolRepository.saveAndFlush(employee);
    }


    /**
     * 功能：删除
     *
     * @param request
     */
    public String delete(SimpleRequest request) {
        String id = request.get("id");
        TalentPool employees = talentPoolRepository.findOne(id);
        if (employees == null) throw new RuntimeException("人员档案：" + id + " 在系统中不存在。");
        employees.setState("delete");
        talentPoolRepository.saveAndFlush(employees);
        //employeeRepository.delete(employes);
        return "删除成功！";
    }


    /**
     * 根据身份证号查询
     *
     * @return
     */
    public TalentPool findByIdCard(SimpleRequest request) {
        String idCard = request.get("idCard");
        idCard = idCard.replaceAll(" ", "");
        return talentPoolRepository.findByIdCard(idCard);
    }

    /**
     * 根据手机号查询
     *
     * @param request
     * @return
     */
    public TalentPool findByMobileNumber(SimpleRequest request) {
        String mobileNumber = request.get("mobileNumber");
        mobileNumber = mobileNumber.replaceAll(" ", "");
        if (talentPoolRepository.findByMobileNumber(mobileNumber) != null) {
            return talentPoolRepository.findByMobileNumber(mobileNumber);
        } else {
            return null;
        }
    }

    public TalentPool findByName(SimpleRequest request) {
        String name = request.get("name");
        if (talentPoolRepository.findByName(name).size() != 0) {
            return talentPoolRepository.findByName(name).stream().findFirst().get();
        } else {
            return null;
        }
    }

    //筛选值 为 请选择
    public JSONObject screen(JSONObject object) {
        for (Map.Entry<String, Object> entry : object.entrySet()) {
            if (entry.getValue().equals("请选择")) {
                entry.setValue(null);
            }
        }
        return object;
    }

    public TalentPool saveApp(SimpleRequest request) {
        TalentPool employee;
        Set<EmployeeFamily> employeeFamilyList = new HashSet<>();//家庭成员
        Set<EmployeeEducation> employeeEducationList = new HashSet<>();//教育背景
        Set<EmployeeWorkHistory> employeeWorkHistoryList = new HashSet<>();//工作经历
        Set<EmployeeSkillCertificate> employeeSkillCertificateList = new HashSet<>();//技能证书
        List<String> schoolNameList = new ArrayList<>();
        List<String> familyNameList = new ArrayList<>();
        List<SkillType> skillTypeList = new ArrayList<>();
        List<String> workHistoryList = new ArrayList<>();
        JSONObject jsonObject = request.get("array");
        JSONObject apply = jsonObject.getJSONObject("apply");//应聘信息
        apply = this.screen(apply);
        JSONObject basic = jsonObject.getJSONObject("basic");//个人信息
        basic = this.screen(basic);
        JSONObject contact = jsonObject.getJSONObject("contact");//联系方式
        contact = this.screen(contact);
        JSONObject skills = jsonObject.getJSONObject("skills");//基本技能
        skills = this.screen(skills);
//        JSONObject statement = jsonObject.getJSONObject("statement");//声明
//        statement = this.screen(statement);
        JSONArray familys = jsonObject.getJSONArray("family");//家庭成员
        JSONArray educations = jsonObject.getJSONArray("education");//教育背景
        JSONArray work = jsonObject.getJSONArray("work");//工作经历
        JSONArray certificate = jsonObject.getJSONArray("certificate");//技能证书

        //get
//        JSONObject object0 = jsonObject.getJSONObject(0);
        try {
//            JSONArray sstatement = statement.getJSONArray("statement");
//            String sameTradeKeepOut = statement.getString("company");
//            String relationship = statement.getString("relationship");

            String name = basic.getString("name");
//            String oldName = basic.getString("oldName");
            String idCard = basic.getString("idCard");
            Date idCardTerm = basic.getDate("idCardTerms");
            if (talentPoolRepository.findByIdCard(idCard) != null) {
                employee = talentPoolRepository.findByIdCard(idCard);

                employeeFamilyList = employee.getEmployeeFamilies();
                employeeFamilyList.forEach(employeeFamily -> {
                    familyNameList.add(employeeFamily.getName());
                });

                employeeEducationList = employee.getEmployeeEducations();
                employeeEducationList.forEach(employeeEducation -> {
                    schoolNameList.add(employeeEducation.getSchoolName());
                });

                employeeWorkHistoryList = employee.getEmployeeWorkHistories();
                employeeWorkHistoryList.forEach(employeeWorkHistory -> {
                    workHistoryList.add(employeeWorkHistory.getWorkUnit());
                });

                employeeSkillCertificateList = employee.getEmployeeSkillCertificates();
                employeeSkillCertificateList.forEach(employeeSkillCertificate -> {
                    skillTypeList.add(employeeSkillCertificate.getSkillType());
                });
            } else {
                employee = new TalentPool();
            }
            String sex = basic.getString("sex");
            Integer age = basic.getInteger("age");//年龄
            Date birthday = basic.getDate("birthday");//生日
            if (birthday == null) {        //如果生日为空，使用身份证重新截取生日
                String year = idCard.substring(6, 10);   //调用substring方法返回相关字段，注意索引从0开始
                String month = idCard.substring(10, 12); //获取月份
                String day = idCard.substring(12, 14);   //获取天数
                String temp = year + "-" + month + "-" + day;
                DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");//定义一个时间转换格式“年-月-日”
                try {     //捕获类型转换（解析）异常
                    birthday = fmt.parse(temp); //1993-10-17
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            Double height = basic.getDouble("height");//身高
            Double weight = basic.getDouble("weight");//体重
            String nativePlace = basic.getString("nativePlace");//籍贯
            String nation = basic.getString("nation");//民族
            String bloodType = basic.getString("bloodType");//血型
            String censusRegNature = basic.getString("censusRegNature");//户口性质
            String theOnlyChild = basic.getString("theOnlyChild");//独生子女
            String maritalState = basic.getString("maritalState");//婚姻状况
            String fertility = basic.getString("fertility");//是否生育
            String politicalVisage = basic.getString("politicalVisage");//政治面貌

            String driver = basic.getString("driver");//是否有驾驶证
            Date driverTerm = basic.getDate("driverTerm");//驾驶证到期时间

            String soldier = basic.getString("soldier");//是否退役军人

            //       //set
//            if (sstatement!=null && !sstatement.isEmpty()){
//                employee.setStatement(sstatement.toString());
//            }
//
//            if(sameTradeKeepOut!=null && sameTradeKeepOut.equals("是")){
//                employee.setSameTradeKeepOut(true);
//            }else{
//                employee.setSameTradeKeepOut(false);
//            }
//
//            if(relationship!=null && relationship.equals("是")){
//                employee.setHasOtherJob(true);
//            }else{
//                employee.setHasOtherJob(false);
//            }
            employee.setName(name);
//            employee.setNameBefore(oldName);
            employee.setIdCard(idCard);
            employee.setIdCardTerm(idCardTerm);
            employee.setDriverTerm(driverTerm);
            if (driver != null && driver.equals("有")) {
                employee.setDriver(true);
            } else {
                employee.setDriver(false);
            }

            if (soldier != null && soldier.equals("是")) {
                employee.setSoldier(true);
            } else {
                employee.setSoldier(false);
            }

            employee.setAge(age);
            List<Enumeration> sexList = enumerationRepository.findByType("sex");
            sexList.forEach(enumeration -> {
                if (enumeration.getDescription().equals(sex)) {
                    employee.setSex(enumeration);
                }
            });
            employee.setBirthday(birthday);
            employee.setHeight(height);
            employee.setWeight(weight);
            employee.setNativePlace(nativePlace);
            List<Enumeration> nationList = enumerationRepository.findByType("nation");
            nationList.forEach(enumeration -> {
                if (enumeration.getDescription().equals(nation)) {
                    employee.setNation(enumeration);
                }
            });
            List<Enumeration> bloodTypeList = enumerationRepository.findByType("bloodType");
            bloodTypeList.forEach(enumeration -> {
                if (enumeration.getDescription().equals(bloodType)) {
                    employee.setBloodType(enumeration);
                }
            });
            List<Enumeration> censusRegNatureList = enumerationRepository.findByType("censusRegNature");
            censusRegNatureList.forEach(enumeration -> {
                if (enumeration.getDescription().equals(censusRegNature)) {
                    employee.setCensusRegNature(enumeration);
                }
            });
            if (theOnlyChild != null) {
                if (theOnlyChild.equals("独生子女")) {
                    employee.setTheOnlyChild(true);
                } else {
                    employee.setTheOnlyChild(false);
                }
            }
            enumerationRepository.findByType("fertility").forEach(enumeration -> {
                if (enumeration.getDescription().equals(fertility)) {
                    employee.setFertility(enumeration);
                }
            });
            List<Enumeration> maritalStateList = enumerationRepository.findByType("maritalState");
            maritalStateList.forEach(enumeration -> {
                if (enumeration.getDescription().equals(maritalState)) {
                    employee.setMaritalState(enumeration);
                }
            });
            List<Enumeration> politicalVisageList = enumerationRepository.findByType("politicalVisage");
            politicalVisageList.forEach(enumeration -> {
                if (enumeration.getDescription().equals(politicalVisage)) {
                    employee.setPoliticalVisage(enumeration);
                }
            });

            //get
            String mobileNumber = basic.getString("mobileNumber");//手机号
            mobileNumber = mobileNumber.replaceAll(" ", "");
            String qqNumber = contact.getString("qqNumber");//QQ
            String email = contact.getString("email");//邮箱
            String postalAddress = contact.getString("postalAddress");//现住址
            String mailAddress = contact.getString("mailAddress");//邮寄地址
            String contactMan = contact.getString("contact");//紧急联系人
            String emergency = contact.getString("emergency");//紧急联系人关系
            String contactPhone = contact.getString("contactPhone");//紧急联系人电话
            contactPhone = contactPhone.replaceAll(" ", "");
//            String telephone = contact.getString("telephone");//固定电话
            String idAddress = contact.getString("idAddress");//身份证地址
            //set
            TalentPool talentPool = talentPoolRepository.findByMobileNumber(mobileNumber);
            if (talentPool != null && !talentPool.getIdCard().equals(idCard)) throw new RuntimeException("手机号码被占用");
            employee.setMobileNumber(mobileNumber);
            employee.setQqNumber(qqNumber);
            employee.setEmail(email);
            employee.setPostalAddress(postalAddress);
            employee.setMailAddress(mailAddress);
            employee.setContact(contactMan);
            employee.setContactRelation(emergency);
            employee.setContactPhone(contactPhone);
//            employee.setTelephone(telephone);
            employee.setIdCardAddress(idAddress);

            //get
            String license = skills.getString("license");//驾照
            String skilled = skills.getString("skilled");//熟练程度
//            String qualification = skills.getString("qualification");//从业资格证
            String mandarin = skills.getString("mandarin");//普通话
            String englishLevel = skills.getString("englishLevel");//英语等级(model里没有)
//            String localDialectLevel = skills.getString("localDialectLevel");//地方语言（model里没有）
            Integer typingSpeed = skills.getInteger("typingSpeed");//打字熟练程度（model 里是int）
            if (typingSpeed != null) {
                if (typingSpeed.toString().length() > 8) {
                    throw new RuntimeException("请检查【打字速度】输入值，当前输入值为：" + typingSpeed);
                }
            }

            String ime = skills.getString("ime");//输入法(model里没有)
            JSONArray fun = skills.getJSONArray("fun");//常用函数（model里没有）
            JSONArray office = skills.getJSONArray("office");//办公软件
            JSONArray design = skills.getJSONArray("design");//设计软件
            //set
            enumerationRepository.findByType("driverLicenseType").forEach(enumeration -> {
                if (enumeration.getDescription().equals(license)) {
                    employee.setDriverLicenseType(enumeration);
                }
            });
            if (skilled != null && skilled.equals("熟练")) {
                employee.setSkilled(true);
            } else {
                employee.setSkilled(false);
            }
//            employee.setTitle(qualification);
            enumerationRepository.findByType("mandarinLevel").forEach(enumeration -> {
                if (enumeration.getDescription().equals(mandarin)) {
                    employee.setMandarinLevel(enumeration);
                }
            });
            employee.setEnglishLevel(englishLevel);
//            enumerationRepository.findByType("localDialectLevel").forEach(enumeration -> {
//                if (enumeration.getDescription().equals(localDialectLevel)) {
//                    employee.setLocalDialectLevel(enumeration);
//                }
//            });
            if (typingSpeed != null) employee.setTypingSpeed(typingSpeed);
            enumerationRepository.findByType("ime").forEach(enumeration -> {
                if (enumeration.getDescription().equals(ime)) {
                    employee.setIme(enumeration);
                }
            });

            Set<Enumeration> functions = new HashSet<>();
            for (int i = 0; i < fun.size(); i++) {
                String funString = fun.getString(i);
                enumerationRepository.findByType("function").forEach(enumeration -> {
                    if (enumeration.getDescription().equals(funString)) {
                        functions.add(enumeration);
                    }
                });
            }
            employee.FunctionsToApp(toConvertReason(functions));
            Set<Enumeration> offices = new HashSet<>();
            for (int i = 0; i < office.size(); i++) {
                String officeString = office.getString(i);
                enumerationRepository.findByType("office").forEach(enumeration -> {
                    if (enumeration.getDescription().equals(officeString)) {
                        offices.add(enumeration);
                    }
                });
            }
            employee.OfficeToApp(toConvertReason(offices));
            Set<Enumeration> designSoftwares = new HashSet<>();
            for (int i = 0; i < design.size(); i++) {
                String designString = design.getString(i);
                enumerationRepository.findByType("designSoftware").forEach(enumeration -> {
                    if (enumeration.getDescription().equals(designString)) {
                        designSoftwares.add(enumeration);
                    }
                });
            }
            employee.DesignSoftwareToApp(toConvertReason(designSoftwares));
            //
            //        JSONArray object3 = jsonObject.getJSONArray(3);
            for (int i = 0; i < certificate.size(); i++) {
                EmployeeSkillCertificate skillCertificate = new EmployeeSkillCertificate();
                skillCertificate.setId(Integer.valueOf(SpringManager.getBean(SequenceService.class).getId(skillCertificate.CONST_TABLE_NAME)));
                JSONObject object = certificate.getJSONObject(i);
                object = this.screen(object);
//                String skillNum = object.getString("skillNum");//技能证书号
                String SkillCertificate = object.getString("certificate");//技能证书类型
                String department = object.getString("department");//发证机关
//                String degree = object.getString("degree");//熟练程度
//                String explain = object.getString("explain");//说明
                Date award = object.getDate("award");//颁发日期
                Integer years = object.getInteger("years");//有效年限
                String record = object.getString("record");//是否备案
                List<SkillType> SkillTypeList = skillTypeRepository.findByName(SkillCertificate);
                if (!skillTypeList.contains(SkillTypeList.get(SkillTypeList.size() - 1))) {
                    skillCertificate.setTalentPool(employee);
//                    skillCertificate.setCertNumber(skillNum);

                    DateUtil.add(new Date(), Calendar.MONTH, 1);

                    if (SkillTypeList != null)
                        skillCertificate.setSkillType(SkillTypeList.get(SkillTypeList.size() - 1));
                    skillCertificate.setIssuingOrgan(department);
//                    skillCertificate.setQualification(degree);
//                    skillCertificate.setDescription(explain);
                    skillCertificate.setIssuingDate(award);
                    if (years!=null)skillCertificate.setEffectiveAge(years);
                    if (record!=null && record.equals("是")){
                        skillCertificate.setHasRecord(true);
                    }else {
                        skillCertificate.setHasRecord(false);
                    }
                    employeeSkillCertificateList.add(skillCertificate);
                }

            }
            employee.setEmployeeSkillCertificates(employeeSkillCertificateList);

            for (int i = 0; i < familys.size(); i++) {
                EmployeeFamily family = new EmployeeFamily();//家庭成员
                String code = sequenceService.getId("hr_Employee_Family");//获取序列
                JSONObject object = familys.getJSONObject(i);
                object = this.screen(object);
                //get
                String Fname = object.getString("name");//姓名
//                Date birthday2 = object.getDate("birthday");//
                int age1 = object.getIntValue("age");
                String relation = object.getString("relation");//关系
                String company = object.getString("company");//工作单位
                String position = object.getString("position");//所在单位职务
                String phone = object.getString("phone");//手机
                phone = phone.replaceAll(" ", "");
                //set
                if (!familyNameList.contains(Fname)) {
                    family.setId(Long.valueOf(code));
                    family.setName(Fname);
                    family.setTalentPool(employee);
                    enumerationRepository.findByType("relation").forEach(enumeration -> {
                        if (enumeration.getDescription().equals(relation)) {
                            family.setRelation(enumeration);
                        }
                    });
                    family.setWorkUnit(company);
                    family.setJobs(position);
                    family.setAge(age1);
//                    family.setBirthday(birthday2);
                    family.setMobileNumber(phone);
                    employeeFamilyList.add(family);
                }
            }
            employee.setEmployeeFamilies(employeeFamilyList);

            //        JSONObject object4 = jsonObject.getJSONObject(4);
            //
            Date time = apply.getDate("time");//可到岗时间
            String between = apply.getString("between");//推荐人关系
            String referees = apply.getString("referees");//推荐人
            String channel = apply.getString("channel");//招聘渠道
            String accommodation = apply.getString("accommodation");//需要住员工宿舍（model里没有）加
            JSONArray notAccept = apply.getJSONArray("notAccept");//最不能接受的（model里没有）加
//            JSONArray security = apply.getJSONArray("security");//社保意向（model里没有）加
//            String security = apply.getString("security");//社保意向（model里没有）加
//            String plan = apply.getString("plan");//职业规划（model里没有）加
//            String salary = apply.getString("salary");//薪水
            JSONArray accept = apply.getJSONArray("accept");//能接受的工作地点（model里没有）期望工作地点
            String post = apply.getString("post");//职位性质（model里没有）不加
            String month = apply.getString("month");//期望月收入（model里没有） 加
            String position = apply.getString("position");//应聘职位（model里没有）加 string
            JSONObject deptValue = apply.getJSONObject("deptValue");
            String deptId = deptValue.getString("DEPTID");
            if (!ObjectUtils.isEmpty(deptId)){
                Dept dept = deptRepository.findOne(deptId);
                if (!ObjectUtils.isEmpty(dept)){
                    employee.setDept(dept);
                }
            }

            employee.setAvailability(time);
            employee.setCognitiveEmployee(referees);
            employee.setCognitiveRelation(between);
            List<RecruitChannel> recruitChannelList = recruitChannelRepository.findByName(channel);
            if (recruitChannelList != null && !recruitChannelList.isEmpty())
                employee.setRecruitChannel(recruitChannelList.get(recruitChannelList.size() - 1));
//            if (accommodation != null && accommodation.equals("住")) {
//                employee.setLiveDormitory(true);
//            } else {
//                employee.setLiveDormitory(false);
//            }
            Set<Enumeration> notAcceptSet = new HashSet<>();
            for (int i = 0; i < notAccept.size(); i++) {
                String notAccept2 = notAccept.getString(i);
                enumerationRepository.findByType("unacceptable").forEach(enumeration -> {
                    if (enumeration.getDescription().equals(notAccept2)) {
                        notAcceptSet.add(enumeration);
                    }
                });
            }
            employee.unacceptablesToApp(toConvertReason(notAcceptSet));
            Set<Enumeration> securitySet = new HashSet<>();
//            if (security != null) {
//                for (int i = 0; i < security.size(); i++) {
//                    String securityString = security.getString(i);
//                    enumerationRepository.findByType("chooseSocialSecurity").forEach(enumeration -> {
//                        if (enumeration.getDescription().equals(securityString)) {
//                            securitySet.add(enumeration);
//                        }
//                    });
//                }
//            }

            Set<Enumeration> differentWorksSet = new HashSet<>();
            if (!CollectionUtils.isEmpty(accept)) {
                for (int i = 0; i < accept.size(); i++) {
                    String accept2 = accept.getString(i);
                    enumerationRepository.findByType("differentWorks").forEach(enumeration -> {
                        if (enumeration.getDescription().equals(accept2)) {
                            differentWorksSet.add(enumeration);
                        }
                    });
                }
                employee.DifferentWorksToApp(toConvertReason(differentWorksSet));
            }

//            employee.setchooseSocialSecuritySet(securitySet);
            employee.chooseSocialSecurityToApp(toConvertReason(securitySet));
//            employee.setDevelopment(plan);
//            employee.setBasePay(salary);
//            employee.setDifferentWorks(accept);
            employee.setNatureOfJob(post);
            employee.setMonthIncome(month);
            employee.setApplicationJob(position);
            //
            //        JSONArray object5 = jsonObject.getJSONArray(5);
            for (int i = 0; i < work.size(); i++) {
                EmployeeWorkHistory workHistory = new EmployeeWorkHistory();//工作经历
                String code = sequenceService.getId("hr_Employee_Work_History");//获取序列
                JSONObject object = work.getJSONObject(i);
                object = this.screen(object);
                //get
                String units = object.getString("units");//工作单位名称
                Date inductions = object.getDate("inductions");//入职日期
                Date departures = object.getDate("departures");//离职日期
                String Wposition = object.getString("position");//担任职务
                Double Wsalary = object.getDouble("salary");//底薪
                Double royalty = object.getDouble("royalty");//提成
                String referencesPhone = object.getString("referencesPhone");//证明人手机
                if (referencesPhone != null) referencesPhone = referencesPhone.replaceAll(" ", "");
                String Wdepartment = object.getString("department");//所在部门
                String why = object.getString("why");//离职原因
                String references = object.getString("references");//证明人
                String referencesPosition = object.getString("referencesPosition");//证明人职务
                //set
                if (!workHistoryList.contains(units)) {
                    workHistory.setId(Long.valueOf(code));
                    workHistory.setTalentPool(employee);
                    workHistory.setWorkUnit(units);
                    workHistory.setStartDate(inductions);
                    workHistory.setEndDate(departures);
                    workHistory.setJobs(Wposition);
                    workHistory.setBaseSalary(Wsalary);
                    workHistory.setCommission(royalty);
                    workHistory.setReterencePhone(referencesPhone);
                    workHistory.setBranch(Wdepartment);
                    workHistory.setQuitCause(why);
                    workHistory.setReterence(references);
                    workHistory.setReterenceJobs(referencesPosition);
                    employeeWorkHistoryList.add(workHistory);
                }
            }
            employee.setEmployeeWorkHistories(employeeWorkHistoryList);
            //
            //        JSONArray object6 = jsonObject.getJSONArray(6);
            for (int i = 0; i < educations.size(); i++) {
                EmployeeEducation education = new EmployeeEducation();
                String code = sequenceService.getId("hr_Employee_Education");//获取序列
                JSONObject object = educations.getJSONObject(i);
                object = this.screen(object);
                //get
                String units = object.getString("units");//学校/培训机构名称
                Date starts = object.getDate("starts");//入学日期
                Date ends = object.getDate("ends");//毕业日期
                String professional = object.getString("professional");//专业名称
                String Ecertificate = object.getString("certificate");//大专及以上学历证书编号
                String degreeNum = object.getString("degreeNum");//学位证书号
                String degree = object.getString("degree");//学历
                String nature = object.getString("nature");//学历性质
                String graduation = object.getString("graduation");//毕业证
                //set
                if (!schoolNameList.contains(units)) {
                    education.setId(Long.valueOf(code));
                    education.setTalentPool(employee);
                    education.setSchoolName(units);
                    education.setStartDate(starts);
                    education.setEndDate(ends);
                    education.setSpecialty(professional);
                    education.setEducationCertificateNo(Ecertificate);
                    education.setDegreeCertificateNo(degreeNum);

                    enumerationRepository.findByType("employeeEducationDegree").forEach(enumeration -> {
                        if (enumeration.getDescription().equals(degree)) {
                            education.setDegree(enumeration);
                        }
                    });
                    enumerationRepository.findByType("educationalType").forEach(enumeration -> {
                        if (enumeration.getDescription().equals(nature)) {
                            education.setEducationalType(enumeration);
                        }
                    });
                    if (graduation != null && graduation.equals("有")) {
                        education.setHasDiploma(true);
                    } else {
                        education.setHasDiploma(false);
                    }
                    employeeEducationList.add(education);
                }
            }
            employee.setEmployeeEducations(employeeEducationList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        return employee;

        employee.setCommitDate(new Date());
        employee.setCommitQty(employee.getCommitQty() + 1);
        return talentPoolRepository.saveAndFlush(employee);
    }

    private String toConvertReason(Set<Enumeration> persons) {
        StringBuffer sb = new StringBuffer();
        for (Enumeration enumeration : persons) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append(enumeration.getId());
            sb.append("|");
            sb.append(enumeration.getDescription());  // 格式 id|description;
        }
        return sb.toString();
    }

    /**
     * 根据手机号码和身份证判断
     *
     * @param request
     * @return
     */
    public Map<String, Boolean> findByIdCardAndPhone(SimpleRequest request) {
        Map<String, Boolean> map = new HashMap<>();
        TalentPool talentPool = findByMobileNumber(request);
        TalentPool talentPool2 = findByIdCard(request);
        if (talentPool2 != null) {
            if (talentPool != null) {
                if (talentPool == talentPool2) {
                    map.put("mas", true);
                } else {
                    map.put("mas", false);
                }
            } else {
                map.put("mas", true);
            }
        } else {
            if (talentPool != null) {
                map.put("mas", false);
            } else {
                map.put("mas", true);
            }
        }
        return map;

    }

    /**
     * 查询所有--权限
     *
     * @param request
     * @return
     */
    public Map authFindAll(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        int maxNum = jsonObject.getInteger("size");
        Post post = postRepository.findOne(request.getPostId());
        Branch dept = post.getBranch();

        String id = null;
        String name = null;
        String mobileNulber = null;
        JSONArray condition = (JSONArray) jsonObject.get("condition");
        if (!CollectionUtils.isEmpty(condition)) {
            for (int i = 0; i < condition.size(); i++) {
                JSONObject object = (JSONObject) condition.get(i);
                if ("id".equals(object.get("field"))) {
                    id = object.get("value").toString();
                }
                if ("name".equals(object.get("field"))) {
                    name = object.get("value").toString();
                }
                if ("mobileNumber".equals(object.get("field"))) {
                    mobileNulber = object.get("value").toString();
                }
            }
        }

        if (post.getLocalPermit().getLocalPermitItems().size() <= 1){
            Page<TalentPool> talentPools = talentPoolRepository.findAll(JpaDsl.toCriteriaIgnoreNull(
                    "id", "EQ", id,
                    "name", "LIKE", name,
                    "mobileNumber", "EQ", mobileNulber), PageRequest.of(jsonObject.getInteger("page"), maxNum, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", talentPools.getContent());
        }else {
            Page<TalentPool> talentPools = talentPoolRepository.findAll(JpaDsl.toCriteriaIgnoreNull(
                    "dept.id", "EQ", dept.getId(),
                    "id", "EQ", id,
                    "name", "LIKE", name,
                    "mobileNumber", "EQ", mobileNulber), PageRequest.of(jsonObject.getInteger("page"), maxNum, Sort.by(Sort.Direction.DESC, "id")));
            return MapUtil.mapper("content", talentPools.getContent());
        }
    }


}
